<template>
  <div class="app-container home">
    <el-card shadow="hover">
      <el-container>
        <el-main>
          <el-row>
            <el-col :span="1.5">
              <el-button :loading="saveButtonLoading" type="primary" plain icon="Select" v-hasPermi="['system:role:sheetFormAuth']" @click="saveSheetAuth">表单授权</el-button>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="margin-top: 20px;">
            <!-- 角色模块 -->
            <el-col :span="4">
              <!-- 搜索框 -->
              <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
                <el-form-item label="角色名称" prop="roleName">
                  <el-input v-model="queryParams.roleName" placeholder="请输入角色名称" clearable @keyup.enter="handleQuery" />
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" @click="handleQuery" icon="Search">搜索</el-button>
                  <el-button @click="resetQuery" icon="Refresh">重置</el-button>
                </el-form-item>
              </el-form>

              <!-- 角色列表 -->
              <el-table ref="roleTableRef" highlight-current-row v-loading="loading" :data="roleList" @current-change="handleRoleCurrentChange">
                <el-table-column label="角色名称" prop="roleName" :show-overflow-tooltip="true" width="150" />
              </el-table>

              <!-- 分页 -->
              <pagination
                v-if="total > 0"
                :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                layout="total, prev, pager, next"
                @pagination="getRoleList"
              />
            </el-col>

            <!-- 表单模块 -->
            <el-col :span="8">
              <!-- 搜索框 -->
              <el-form :model="querySheetFormParams" ref="querySheetFormRef" :inline="true" label-width="68px">
                <el-form-item label="应用名称" prop="name">
                  <el-input v-model="querySheetFormParams.name" placeholder="请输入应用名称" clearable @keyup.enter="handleSheetFormQuery" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleSheetFormQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetSheetFormQuery">重置</el-button>
                </el-form-item>
              </el-form>

              <!-- 列表 -->
              <el-table
                v-loading="sheetFormLoading"
                :data="sheetFormList"
                row-key="sheetFormId"
                :default-expand-all="isExpandAll"
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                ref="sheetFormTableRef"
                highlight-current-row
                @row-click="sheetFormRowClick"
                height="600"
              >
                <el-table-column label="表单名称" text-align="center" prop="name" />
                <el-table-column label="显示名称" text-align="center" prop="showName" />
                <el-table-column label="授予" text-align="center" prop="isAuth">
                  <template #default="scope">
                    <el-checkbox v-model="scope.row.isAuth" true-label="Y" false-label="N" @change="sheetFormAuthChange(scope.row)"/>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>

            <!-- 应用按钮模块 -->
            <el-col :span="12">
              <el-tabs v-model="activeName" class="demo-tabs">
                <el-tab-pane label="字段授权" name="field">
                  <el-table v-loading="sheetFieldLoading" :data="sheetFieldList" height="600">
                    <el-table-column label="字段名" text-align="center" prop="fieldName" />
                    <el-table-column label="简体中文" text-align="center" prop="chineseName" />
                    <el-table-column label="授予" text-align="center" prop="isAuth">
                      <template #header>
                        <span>授予</span>
                        <el-button size="small" type="primary" text @click="checkAll('isAuth')">全选</el-button>
                      </template>
                      <template #default="scope">
                        <el-checkbox v-model="scope.row.isAuth" :disabled="checkFlag" true-label="Y" false-label="N" />
                      </template>
                    </el-table-column>
                    <el-table-column label="隐藏" text-align="center" prop="isHidden">
                      <template #header>
                        <span>隐藏</span>
                        <el-button size="small" type="primary" text @click="checkAll('isHidden')">全选</el-button>
                      </template>
                      <template #default="scope">
                        <el-checkbox v-model="scope.row.isHidden" :disabled="scope.row.isAuth !== 'Y'" true-label="Y" false-label="N" />
                      </template>
                    </el-table-column>
                    <el-table-column label="编辑" text-align="center" prop="isEdit">
                      <template #header>
                        <span>编辑</span>
                        <el-button size="small" type="primary" text @click="checkAll('isEdit')">全选</el-button>
                      </template>
                      <template #default="scope">
                        <el-checkbox v-model="scope.row.isEdit" :disabled="scope.row.isAuth !== 'Y'" true-label="Y" false-label="N" />
                      </template>
                    </el-table-column>
                  </el-table>
                </el-tab-pane>
                <el-tab-pane label="按钮授权" name="button">
                  <!-- 应用按钮列表 -->
                  <el-table v-loading="buttonLoading" :data="sheetButtonList" >
                    <el-table-column label="名称" text-align="center" prop="showName" />
                    <el-table-column label="授予" prop="isAuth">
                      <template #default="scope">
                        <el-checkbox v-model="scope.row.isAuth" :disabled="checkFlag" true-label="Y" false-label="N" />
                      </template>
                    </el-table-column>
                  </el-table>

                </el-tab-pane>
              </el-tabs>

            </el-col>
          </el-row>

        </el-main>
      </el-container>
    </el-card>
  </div>
</template>


<script setup name="SheetFormAuth" lang="ts">
import { listRole } from "@/api/system/role";
import { RoleForm, RoleQuery, RoleVO } from "@/api/system/role/types";
import { SheetButtonVO } from "@/api/sheet/sheetButton/types";
import { listAllSheetButton } from "@/api/sheet/sheetButton";
import { SheetFormVO } from "@/api/sheet/sheetForm/types";
import { listSheetForm } from "@/api/sheet/sheetForm";
import { SheetFieldVO } from "@/api/sheet/sheetField/types";
import { listSheetFieldAll } from "@/api/sheet/sheetField";
import { getSheetFormAuthData, saveSheetFormAuthData } from "@/api/sheet/sheetAuth";
import { SheetFormAuthData, SheetFormAuthVO, SheetButtonAuthVO, SheetFormFieldAuthVO } from "@/api/sheet/sheetAuth/types";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const activeName = ref('field');
const saveButtonLoading = ref(false);

/** 角色相关参数 */
const roleList = ref<RoleVO[]>();
const loading = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const initForm: RoleForm = {
  roleId: undefined,
  roleSort: 1,
  status: '0',
  roleName: '',
  roleKey: '',
  menuCheckStrictly: true,
  deptCheckStrictly: true,
  remark: '',
  dataScope: '1',
  menuIds: [],
  deptIds: [],
};
const data = reactive<PageData<RoleForm, RoleQuery>>({
  form: { ...initForm },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    roleName: '',
    roleKey: '',
    status: '',
  },
  rules: {
    roleName: [{ required: true, message: "角色名称不能为空", trigger: "blur" }],
    roleKey: [{ required: true, message: "权限字符不能为空", trigger: "blur" }],
    roleSort: [{ required: true, message: "角色顺序不能为空", trigger: "blur" }]
  }
});
const { form, queryParams, rules } = toRefs(data);

/** 当前选中角色 */
const currentRoleRow = ref();
/** 当前选中表单 */
const currentSheetFormRow = ref();

/** 表单相关参数 */
const sheetFormLoading = ref(false);
const sheetFormList = ref<SheetFormVO[]>([]);
const sheetFormTableRef = ref<ElTableInstance>()
const querySheetFormRef = ref<ElFormInstance>();
const isExpandAll = ref(true);
const querySheetFormParams = ref({
  pageNum: 1,
  pageSize: 10,
  name: undefined,
  selectAuth: 'Y',
  roleId: '',
});

/** 应用按钮相关参数 */
const sheetButtonList = ref<SheetButtonVO[]>([]);
const buttonLoading = ref(false);
const queryButtonParams = ref({
  pageNum: 1,
  pageSize: 10,
  bindId: '',
  selectAuth: 'Y',
  roleId: undefined,
});

/** 字段列表相关参数 */
const sheetFieldLoading = ref(false);
const sheetFieldList = ref<SheetFieldVO[]>([]);
const querySheetFieldParams = ref({
  pageNum: 1,
  pageSize: 10,
  sheetId: '',
  formStatus: 'Y',
  roleId: undefined,
});

/** 应用表单授权记录 */
const sheetFormAuthList = ref<SheetFormVO[]>([]);
/** 应用字段授权记录 */
const sheetFieldAuthList = ref<SheetFormFieldAuthVO[]>([]);
/** 应用表单按钮授权记录 */
const sheetButtonAuthList = ref<SheetButtonAuthVO[]>([]);
/** 提交授权数据 */
const authData = ref<SheetFormAuthData>({
  roleId: '',
  sheetFormAuthList: [],
  sheetFieldAuthList: [],
  sheetButtonAuthList: [],
});

/** 字段、按钮是否可选择 */
const checkFlag = ref(true);

/**
 * 查询角色列表
 */
const getRoleList = () => {
  loading.value = true
  listRole(queryParams.value).then(res => {
    roleList.value = res.rows
    total.value = res.total
    loading.value = false
  })
}

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getRoleList();
}

/** 重置 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 当前选中角色 */
const handleRoleCurrentChange = (val: RoleVO) => {
  if (val){
    currentRoleRow.value = val
    querySheetFormParams.value.roleId = val.roleId as string;
    querySheetFormParams.value.pageNum = 1;
    querySheetFormParams.value.pageSize = 10;
    // 获取应用表单列表
    getSheetFormList();
    // 获取角色授权表单数据
    getSheetFormAuthDataByRoleId(val.roleId);
  }

  sheetFormList.value = [];
  sheetFieldList.value = [];
  sheetButtonList.value = [];
}

/** 获取应用表单列表 */
const getSheetFormList = async () => {
  sheetFormLoading.value = true;
  const res = await listSheetForm(querySheetFormParams.value);
  const data = proxy?.handleTree<SheetFormVO>(res.data, "sheetFormId", "pid");
  if (data) {
    sheetFormList.value = data;
    // 设置已授权的表单
    sheetFormAuthList.value = res.data.filter(item => item.isAuth == 'Y');

    let row;
    if (sheetFormAuthList.value.length > 0){
      row = sheetFormAuthList.value[0];
    } else if (sheetFormList.value.length > 0){
      row = sheetFormList.value[0];
    }
    if (row){
      sheetFormTableRef.value?.setCurrentRow(row)
      sheetFormRowClick(row)
      currentSheetFormRow.value = row;

      // 设置字段、按钮是否可选择
      if (row.isAuth == 'Y'){
        checkFlag.value = false;
      } else {
        checkFlag.value = true;
      }
    }
  }
  sheetFormLoading.value = false;
}

/** 获取角色授权表单数据 */
const getSheetFormAuthDataByRoleId = async (roleId: string | number) => {
  const res = await getSheetFormAuthData(roleId);
  authData.value = res.data;
}


/**
 * 搜索按钮操作
 */
const handleSheetFormQuery = () => {
  querySheetFormParams.value.pageNum = 1;
  getSheetFormList();
}

/** 重置 */
const resetSheetFormQuery = () => {
  querySheetFormRef.value?.resetFields();
  handleSheetFormQuery();
}


/** 应用表单行点击 */
const sheetFormRowClick = (row?: SheetFormVO) =>{
  currentSheetFormRow.value = row;
  queryButtonParams.value.bindId = row?.sheetFormId as string;
  queryButtonParams.value.pageNum = 1;
  queryButtonParams.value.pageSize = 10;
  getButtonList();
  getSheetFieldAllList(row?.sheetId as string);
  sheetButtonAuthList.value = [];

  // 设置字段、按钮是否可选择
  if (row?.isAuth == 'Y'){
    checkFlag.value = false;
  } else {
    checkFlag.value = true;
  }
}

/** 查询应用控件列表 */
const getButtonList = async () => {
  buttonLoading.value = true;
  queryButtonParams.value.roleId = currentRoleRow.value.roleId;
  const res = await listAllSheetButton(queryButtonParams.value);
  sheetButtonList.value = res.data;

  buttonLoading.value = false;
}

/** 应用表单授权事件 */
const sheetFormAuthChange = (row: SheetFormVO) =>{
  if (row.isAuth === 'Y') {
    sheetFormAuthList.value.push(row);
  } else {
    sheetFormAuthList.value.forEach((item,index) => {
      if(item.sheetId == row.sheetId){
        sheetFormAuthList.value.splice(index, 1);
      }
    })
  }

  // 设置字段、按钮是否可选择
  if (row?.isAuth == 'Y'){
    checkFlag.value = false;
  } else {
    checkFlag.value = true;
  }
}

/** 获取表单启用字段 */
const getSheetFieldAllList = async (sheetId: string) => {
  sheetFieldLoading.value = true;
  querySheetFieldParams.value.sheetId = sheetId;
  querySheetFieldParams.value.roleId = currentRoleRow.value.roleId;
  const res = await listSheetFieldAll(querySheetFieldParams.value);
  sheetFieldList.value = res.data;
  sheetFieldList.value.forEach((item) => {
    item.formId = currentSheetFormRow.value?.sheetFormId
  })
  sheetFieldLoading.value = false;
}

/** 设置全选 */
const checkAll = (type: string) =>{
  sheetFieldList.value.forEach((item) => {
    if (type == 'isAuth') {
      item.isAuth = 'Y';
    } else if (type == 'isHidden'){
      item.isHidden = 'Y';
    } else if (type == 'isEdit'){
      item.isEdit = 'Y';
    }
  })
}

/** 保存应用授权 */
const saveSheetAuth = async () => {

  // 授权表单
  const sheetFormAuthDataList : SheetFormAuthVO[] = new Array();
  sheetFormAuthList.value.forEach((item) => {
    let data: SheetFormAuthVO = {
      roleId: currentRoleRow.value.roleId,
      formId: item.sheetFormId,
    }
    sheetFormAuthDataList.push(data);
  })

  // 授权字段
  getSheetFieldAuthList();

  // 授权按钮
  getSheetButtonAuthList();


  const data : SheetFormAuthData = {
    roleId: currentRoleRow.value?.roleId as string,
    sheetFormAuthList: sheetFormAuthDataList,
    sheetFieldAuthList: sheetFieldAuthList.value,
    sheetButtonAuthList: sheetButtonAuthList.value
  }
  console.info("请求参数=>", data)
  await saveSheetFormAuthData(data)
  proxy?.$modal.msgSuccess("操作成功")

  await getSheetFormList()
  saveButtonLoading.value = false;
}

/** 获取需要保存或修改的授权字段 */
const getSheetFieldAuthList = () => {
  sheetFieldAuthList.value = [];
  // 需要删除的授权字段
  const delSheetFieldList = sheetFieldList.value.filter(item => (item.isAuth == 'N' ||item.isAuth == null) && (item.isEdit == 'N' || item.isEdit == null) && (item.isHidden == 'N' || item.isHidden == null) )
  // 需要保存或修改的授权字段
  const saveOrUpdateSheetFieldList = sheetFieldList.value.filter(item => item.isAuth == 'Y' || item.isEdit == 'Y' || item.isHidden == 'Y' )
  // 旧的授权字段
  const oldFieldAuthList = authData.value.sheetFieldAuthList;

  saveOrUpdateSheetFieldList.forEach((item) => {
    let itemOldData = oldFieldAuthList.filter(oldItem => oldItem.fieldId == item.sheetFieldId && oldItem.formId == currentSheetFormRow.value.sheetFormId)
    console.info(currentSheetFormRow.value.sheetFormId)
    if (itemOldData.length == 0){
      let data: SheetFormFieldAuthVO = {
        roleId: currentRoleRow.value.roleId ,
        sheetId: item.sheetId,
        formId: currentSheetFormRow.value.sheetFormId,
        fieldId: item.sheetFieldId,
        isAuth: item.isAuth,
        isEdit: item.isEdit,
        isHidden: item.isHidden,
        handleState: "I"
      }
      sheetFieldAuthList.value.push(data);
    } else {
      itemOldData.forEach((oldItem) => {
        if (oldItem.isAuth != item.isAuth || oldItem.isEdit!= item.isEdit || oldItem.isHidden!= item.isHidden){
          oldItem.handleState = 'U';
          sheetFieldAuthList.value.push(oldItem);
        }
      })
    }
  })

  delSheetFieldList.forEach((item) => {
    let itemOldData = oldFieldAuthList.filter(oldItem => oldItem.fieldId == item.sheetFieldId && oldItem.formId == currentSheetFormRow.value.sheetFormId)
    itemOldData.forEach((oldItem) => {
      oldItem.handleState = 'D';
      sheetFieldAuthList.value.push(oldItem);
    })
  })
}

/** 获取需要保存或修改的授权按钮 */
const getSheetButtonAuthList = () => {
  sheetButtonAuthList.value = [];
  // 旧的授权字段
  const oldButtonAuthData = authData.value.sheetButtonAuthList;
  // 需要删除的授权按钮
  const delButtonList = sheetButtonList.value.filter(item => item.isAuth != 'Y')
  // 需要保存的授权按钮
  const saveButtonList = sheetButtonList.value.filter(item => item.isAuth == 'Y')
  saveButtonList.forEach((item) => {
    let itemOldData = oldButtonAuthData.filter(oldItem => oldItem.sheetButtonId == item.sheetButtonId && oldItem.bindId == currentSheetFormRow.value.sheetFormId)
    if (itemOldData.length == 0){
      let data: SheetButtonAuthVO = {
        roleId: currentRoleRow.value.roleId,
        bindId: item.bindId,
        sheetButtonId: item.sheetButtonId,
        type: 1,
        handleState: "I"
      }
      sheetButtonAuthList.value.push(data);
    }
  })
  delButtonList.forEach((item) => {
    let itemOldData = oldButtonAuthData.filter(oldItem => oldItem.sheetButtonId == item.sheetButtonId && oldItem.bindId == currentSheetFormRow.value.sheetFormId)
    itemOldData.forEach((oldItem) => {
      oldItem.handleState = 'D';
      sheetButtonAuthList.value.push(oldItem);
    })
  })
}

onMounted(() => {
  getRoleList();
});

</script>

